"""
车辆服务模块
处理车辆数据查询和请求逻辑
"""

import time
from data.car_analyzer import CarAnalyzer

class CarService:
    def __init__(self):
        self.analyzer = CarAnalyzer()
        
    def process_car_request(self, ai_response, user_input):
        """
        处理车辆请求
        :param ai_response: AI的响应文本
        :param user_input: 用户的输入文本
        :return: 处理结果字典
        """
        try:
            # 检查是否是二手车相关请求
            if not self._is_car_related_request(user_input):
                return {
                    "should_process": False,
                    "message": None
                }
                
            # 检查是否已收集完需求
            if not self._is_requirements_clear(ai_response):
                return {
                    "should_process": False,
                    "message": None
                }
                
            # 模拟查询延迟
            time.sleep(2)
            
            # 分析需求
            self.analyzer.analyze_requirements(ai_response)
            
            # 获取分析摘要
            analysis = self.analyzer.get_analysis_summary()
            
            # 获取车辆推荐
            cars = self.analyzer.get_car_recommendations()
            
            # 格式化结果
            result_message = self.analyzer.format_recommendations(cars)
            
            return {
                "should_process": True,
                "message": result_message,
                "analysis": analysis,
                "car_count": len(cars)
            }
            
        except Exception as e:
            return {
                "should_process": True,
                "message": "\n\n抱歉，数据查询出现异常，请稍后重试。",
                "error": str(e)
            }
            
    def _is_car_related_request(self, user_input):
        """
        检查是否是二手车相关请求
        :param user_input: 用户输入
        :return: 是否是二手车相关请求
        """
        car_keywords = ["二手车", "买车", "车源", "车型", "价格"]
        return any(keyword in user_input for keyword in car_keywords)
        
    def _is_requirements_clear(self, ai_response):
        """
        检查是否已收集完需求
        :param ai_response: AI响应
        :return: 是否已收集完需求
        """
        return "清晰您的需求" in ai_response 